package com.sinsz.common.condition;

import com.sinsz.common.exception.ApiException;
import com.sinsz.common.exception.DefaultError;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

/**
 * 条件触发器
 * <p>
 *     处理是否启用Bolt
 * </p>
 * @author chenjianbo
 */
public class BoltCondition extends SpringBootCondition {

    private static final String ENABLE_BOLT = "sinsz.common.enable-bolt";
    private static final String BOLT_APPNAME = "sinsz.common.bolt.app-name";

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Boolean enableBolt = context.getEnvironment().getProperty(ENABLE_BOLT, Boolean.class);
        String appName = context.getEnvironment().getProperty(BOLT_APPNAME, String.class);
        enableBolt = enableBolt == null ? false : enableBolt;
        if (enableBolt) {
            if (StringUtils.isEmpty(appName)) {
                throw new ApiException(DefaultError.BOLT_ERROR_01);
            }
        }
        Boolean state = enableBolt && !StringUtils.isEmpty(appName);
        return new ConditionOutcome(
                state,
                "EnableBolt"
        );
    }
}
